package com.giteelou.md;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Security;
import java.util.Enumeration;

public class EncryptUtil {
    public static void main(String[] args) {
        for (Provider provider : Security.getProviders()) {
            System.out.println(provider);
            Enumeration<Object> elements = provider.elements();
            while (elements.hasMoreElements()) {
                System.out.println("\t" + elements.nextElement());
            }
        }
    }

    public static String encrypt(String algorithm, File file) throws NoSuchAlgorithmException, IOException {
        return encrypt(algorithm, file, 2048);
    }

    public static String encrypt(String algorithm, File file, int bufSize) throws NoSuchAlgorithmException, IOException {
        MessageDigest md = MessageDigest.getInstance(algorithm);
        try (InputStream input = new BufferedInputStream(Files.newInputStream(file.toPath(), StandardOpenOption.READ))) {
            byte[] buf = new byte[bufSize];
            int len;
            while ((len = input.read(buf)) != -1) {
                md.update(buf, 0, len);
            }
            return toHexString(md.digest());
        }
    }

    public static String encrypt(String algorithm, String text) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance(algorithm);
        return toHexString(md.digest(text.getBytes()));
    }

    private static String toHexString(byte[] bytes) {
        //return new BigInteger(1, bytes).toString(16); // way 1
        /*StringBuilder builder = new StringBuilder(bytes.length * 2); // way 2
        for (byte b : bytes) {
             builder.append(String.format("%02x", b));
        }
        return builder.toString();*/
        char[] chars = new char[bytes.length * 2]; // way 3
        int i = 0;
        for (byte b : bytes) {
            chars[i++] = Integer.toHexString(b >>> 4 & 0xf).charAt(0);
            chars[i++] = Integer.toHexString(b & 0xf).charAt(0);
        }
        return new String(chars);
    }

}
